package com.ds.iot.log;

import com.ds.cluster.service.SysEventWebManager;
import com.ds.common.JDSException;
import com.ds.common.query.Condition;
import com.ds.common.query.JLuceneIndex;
import com.ds.common.query.JoinOperator;
import com.ds.common.query.Operator;
import com.ds.common.util.DateUtility;
import com.ds.config.ErrorListResultModel;
import com.ds.config.ListResultModel;
import com.ds.config.ResultModel;
import com.ds.iot.DeviceEndPoint;
import com.ds.iot.ZNode;
import com.ds.iot.ct.CtIotFactory;
import com.ds.iot.enums.DeviceStatus;
import com.ds.iot.json.SensorHistoryDataInfo;
import com.ds.iot.log.XUICommandLog;
import com.ds.iot.log.XUISensorLog;
import com.ds.jds.core.esb.EsbUtil;
import com.ds.msg.*;
import com.ds.org.Person;
import com.ds.org.query.MsgConditionKey;
import com.ds.server.OrgManagerFactory;
import com.ds.server.service.SysWebManager;
import com.ds.web.ConnectionLogFactory;
import com.ds.web.RuntimeLog;
import com.ds.web.util.PageUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/iot/log")
public class IotLogService {


    @RequestMapping(value = {"/getSensorCMDLogs"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<XUICommandLog>> getSensorCMDLogs(String sensorieee, String starttime, String endtime) {
        ListResultModel<List<XUICommandLog>> userStatusInfo = new ListResultModel<List<XUICommandLog>>();
        try {
            MsgClient client = MsgFactroy.getInstance().getClient(null, CommandMsg.class);
            Condition<MsgConditionKey, JLuceneIndex> condition = new Condition(MsgConditionKey.MSG_ACTIVITYINSTID, Operator.EQUALS, sensorieee);
            if (starttime != null && !starttime.equals("") && endtime != null && !endtime.equals("")) {
                Condition timeCondition = new Condition(MsgConditionKey.MSG_SENDTIME, Operator.BETWEEN, new Date[]{DateUtility.getDate(starttime), DateUtility.getDate(endtime)});
                condition.addCondition(timeCondition, JoinOperator.JOIN_AND);
            }
            ListResultModel<List<CommandMsg>> commandMsgs = client.getMsgList(condition);
            userStatusInfo = PageUtil.changPageList(commandMsgs, XUICommandLog.class);
        } catch (JDSException e)

        {
            userStatusInfo = new ErrorListResultModel();
            ((ErrorListResultModel) userStatusInfo).setErrcode(e.getErrorCode());
            ((ErrorListResultModel) userStatusInfo).setErrdes(e.getMessage());
        }


        return userStatusInfo;
    }

    @RequestMapping(value = {"/getCMDLogs"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<XUICommandLog>> getCMDLogs(String gwieee, String ieee, String starttime, String endtime, String body) {
        ListResultModel<List<XUICommandLog>> userStatusInfo = new ListResultModel<List<XUICommandLog>>();
        try {
            Condition condition = new Condition(MsgConditionKey.MSG_TYPE, Operator.EQUALS, "COMMAND");
            MsgClient client = MsgFactroy.getInstance().getClient(null, CommandMsg.class);

            if (gwieee != null && !gwieee.equals("")) {
                Condition<MsgConditionKey, JLuceneIndex> gwcondition = new Condition(MsgConditionKey.MSG_PROCESSINSTID, Operator.EQUALS, gwieee);
                condition.addCondition(gwcondition, JoinOperator.JOIN_AND);
            }
            if (ieee != null && !ieee.equals("")) {
                Condition<MsgConditionKey, JLuceneIndex> gwcondition = new Condition(MsgConditionKey.MSG_ACTIVITYINSTID, Operator.EQUALS, ieee);
                condition.addCondition(gwcondition, JoinOperator.JOIN_AND);
            }
            if (body != null && !body.equals("")) {
                Condition<MsgConditionKey, JLuceneIndex> gwcondition = new Condition(MsgConditionKey.MSG_BODY, Operator.LIKE, "%" + body + "%");
                condition.addCondition(gwcondition, JoinOperator.JOIN_AND);
            }

            if (endtime != null && !endtime.equals("")) {
                Condition timeCondition = new Condition(MsgConditionKey.MSG_SENDTIME, Operator.LESS_THAN, endtime);
                condition.addCondition(timeCondition, JoinOperator.JOIN_AND);
            }

            if (starttime != null && !starttime.equals("")) {
                Condition timeCondition = new Condition(MsgConditionKey.MSG_SENDTIME, Operator.GREATER_THAN, starttime);
                condition.addCondition(timeCondition, JoinOperator.JOIN_AND);
            }


            ListResultModel<List<CommandMsg>> commandMsgs = client.getMsgList(condition);
            userStatusInfo = PageUtil.changPageList(commandMsgs, XUICommandLog.class);
        } catch (
                JDSException e)

        {
            userStatusInfo = new ErrorListResultModel();
            ((ErrorListResultModel) userStatusInfo).setErrcode(e.getErrorCode());
            ((ErrorListResultModel) userStatusInfo).setErrdes(e.getMessage());
        }


        return userStatusInfo;
    }


    @RequestMapping(value = {"/getRunTimeLogs"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<RuntimeLog>> getRunTimeLogs(String url, String body, String sessionId, Long time) {
        if (time == null) {
            time = 0L;
        }
        if (url == null || url.equals("")) {
            url = "http://";
        }
        ListResultModel<List<RuntimeLog>> userStatusInfo = new ListResultModel<List<RuntimeLog>>();
        List<RuntimeLog> logs = ConnectionLogFactory.getInstance().findLogs(url, body, sessionId, time);
        userStatusInfo = PageUtil.getDefaultPageList(logs);
        return userStatusInfo;
    }


    @RequestMapping(value = {"/getUDPLogs"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<RuntimeLog>> getUDPLogs(String url, String body, String sessionId, Long time) {
        if (time == null) {
            time = 0L;
        }
        ListResultModel<List<RuntimeLog>> userStatusInfo = new ListResultModel<List<RuntimeLog>>();
        SysWebManager manager = EsbUtil.parExpression(SysWebManager.class);
        SysEventWebManager eventWebManager = EsbUtil.parExpression(SysEventWebManager.class);
        if (url == null || url.equals("")) {
            url = "udp://";
        }else if (url.endsWith("]")){
            url= url.substring(0,url.lastIndexOf(":"));
        }
        ListResultModel<List<RuntimeLog>> logs = eventWebManager.getRunTimeLogs(url, body, sessionId, time);
        userStatusInfo = PageUtil.changPageList(logs, RuntimeLog.class);
        return userStatusInfo;
    }


    @RequestMapping(value = {"/clear"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ResultModel<Boolean> clear(String url) {
        ConnectionLogFactory.getInstance().clear(url);
        ResultModel userStatusInfo = new ResultModel();
        return userStatusInfo;
    }


    @RequestMapping(value = {"/getAlarmLog"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<XUISensorLog>> getAlarmLog(String ieee, String starttime, String endtime, String body) {
        ListResultModel<List<XUISensorLog>> userStatusInfo = new ListResultModel<List<XUISensorLog>>();
        try {
            List<SensorHistoryDataInfo> msgs = new ArrayList<SensorHistoryDataInfo>();
            Condition condition = new Condition(MsgConditionKey.MSG_TYPE, Operator.EQUALS, "ALARM");
            if (ieee != null && !ieee.equals("")) {
                DeviceEndPoint ep = CtIotFactory.getCtIotService().getEndPointByIeee(ieee);
                List<ZNode> znodes = ep.getAllZNodes();
                List<String> znodeIds = new ArrayList<String>();
                Person person = OrgManagerFactory.getOrgManager().getPersonByAccount(ep.getDevice().getBindingaccount());
                for (ZNode znode : znodes) {
                    if (znode.getCreateuiserid().equals(person.getID()) && !znode.getStatus().equals(DeviceStatus.DELETE)) {
                        znodeIds.add(znode.getZnodeid());
                    }
                }
                Condition gwcondition = new Condition(MsgConditionKey.MSG_TYPE, Operator.IN, znodeIds);
                condition.addCondition(gwcondition, JoinOperator.JOIN_AND);
            }
            if (body != null && !body.equals("")) {
                Condition<MsgConditionKey, JLuceneIndex> gwcondition = new Condition(MsgConditionKey.MSG_BODY, Operator.LIKE, "%" + body + "%");
                condition.addCondition(gwcondition, JoinOperator.JOIN_AND);
            }

            if (endtime != null && !endtime.equals("")) {
                Condition timeCondition = new Condition(MsgConditionKey.MSG_SENDTIME, Operator.LESS_THAN, endtime);
                condition.addCondition(timeCondition, JoinOperator.JOIN_AND);
            }

            if (starttime != null && !starttime.equals("")) {
                Condition timeCondition = new Condition(MsgConditionKey.MSG_SENDTIME, Operator.GREATER_THAN, starttime);
                condition.addCondition(timeCondition, JoinOperator.JOIN_AND);
            }

            MsgClient<AlarmMsg> client = MsgFactroy.getInstance().getClient(null, AlarmMsg.class);

            ListResultModel<List<AlarmMsg>> commandMsgs = client.getMsgList(condition);

            userStatusInfo = PageUtil.changPageList(commandMsgs, XUISensorLog.class);

        } catch (Exception e) {
            userStatusInfo = new ErrorListResultModel();
            ((ErrorListResultModel) userStatusInfo).setErrdes(e.getMessage());
        }
        return userStatusInfo;


    }

    @RequestMapping(value = {"/getLog"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<XUISensorLog>> getLog(String ieee, String starttime, String endtime, String body) {
        ListResultModel<List<XUISensorLog>> userStatusInfo = new ListResultModel<List<XUISensorLog>>();
        try {
            List<XUISensorLog> msgs = new ArrayList<XUISensorLog>();
            Condition condition = new Condition(MsgConditionKey.MSG_TYPE, Operator.EQUALS, "SENSOR");
            if (ieee != null && !ieee.equals("")) {

                DeviceEndPoint ep = CtIotFactory.getCtIotService().getEndPointByIeee(ieee);
                List<ZNode> znodes = ep.getAllZNodes();
                List<String> znodeIds = new ArrayList<String>();
                Person person = OrgManagerFactory.getOrgManager().getPersonByAccount(ep.getDevice().getBindingaccount());
                for (ZNode znode : znodes) {
                    if (znode.getCreateuiserid().equals(person.getID()) && !znode.getStatus().equals(DeviceStatus.DELETE)) {
                        znodeIds.add(znode.getZnodeid());
                    }
                }
                if (znodeIds.size() > 0) {
                    Condition gwcondition = new Condition(MsgConditionKey.MSG_ACTIVITYINSTID, Operator.IN, znodeIds);

                    condition.addCondition(gwcondition, JoinOperator.JOIN_AND);
                }


            }

            if (body != null && !body.equals("")) {
                Condition<MsgConditionKey, JLuceneIndex> gwcondition = new Condition(MsgConditionKey.MSG_BODY, Operator.LIKE, "%" + body + "%");
                condition.addCondition(gwcondition, JoinOperator.JOIN_AND);
            }
            if (endtime != null && !endtime.equals("")) {
                Condition timeCondition = new Condition(MsgConditionKey.MSG_SENDTIME, Operator.LESS_THAN, endtime);
                condition.addCondition(timeCondition, JoinOperator.JOIN_AND);
            }

            if (starttime != null && !starttime.equals("")) {
                Condition timeCondition = new Condition(MsgConditionKey.MSG_SENDTIME, Operator.GREATER_THAN, starttime);
                condition.addCondition(timeCondition, JoinOperator.JOIN_AND);
            }


            MsgClient<SensorMsg> client = MsgFactroy.getInstance().getClient(null, SensorMsg.class);


            ListResultModel<List<SensorMsg>> commandMsgs = client.getMsgList(condition);

            userStatusInfo = PageUtil.changPageList(commandMsgs, XUISensorLog.class);

        } catch (Exception e) {
            userStatusInfo = new ErrorListResultModel();
            ((ErrorListResultModel) userStatusInfo).setErrdes(e.getMessage());
        }
        return userStatusInfo;


    }


    @RequestMapping(value = {"/getDataLogs"}, method = {RequestMethod.GET, RequestMethod.POST})
    public @ResponseBody
    ListResultModel<List<XUIDataLog>> getDataLogs(String gwieee, String ieee, String starttime, String endtime, String body) {
        ListResultModel<List<XUIDataLog>> userStatusInfo = new ListResultModel<List<XUIDataLog>>();
        Condition condition = new Condition(MsgConditionKey.MSG_TYPE, Operator.EQUALS, "LOG");
        try {
            List<XUIDataLog> modules = new ArrayList<XUIDataLog>();
            MsgClient<LogMsg> client = MsgFactroy.getInstance().getClient(null, LogMsg.class);

            if (gwieee != null && !gwieee.equals("")) {
                Condition<MsgConditionKey, JLuceneIndex> gwcondition = new Condition(MsgConditionKey.MSG_PROCESSINSTID, Operator.EQUALS, gwieee);
                condition.addCondition(gwcondition, JoinOperator.JOIN_AND);
            }

            if (ieee != null && !ieee.equals("")) {
                Condition<MsgConditionKey, JLuceneIndex> gwcondition = new Condition(MsgConditionKey.MSG_ACTIVITYINSTID, Operator.EQUALS, ieee);
                condition.addCondition(gwcondition, JoinOperator.JOIN_AND);
            }

            if (body != null && !body.equals("")) {
                Condition<MsgConditionKey, JLuceneIndex> gwcondition = new Condition(MsgConditionKey.MSG_BODY, Operator.LIKE, "%" + body + "%");
                condition.addCondition(gwcondition, JoinOperator.JOIN_AND);
            }

            if (endtime != null && !endtime.equals("")) {
                Condition timeCondition = new Condition(MsgConditionKey.MSG_SENDTIME, Operator.LESS_THAN, endtime);
                condition.addCondition(timeCondition, JoinOperator.JOIN_AND);
            }

            if (starttime != null && !starttime.equals("")) {
                Condition timeCondition = new Condition(MsgConditionKey.MSG_SENDTIME, Operator.GREATER_THAN, starttime);
                condition.addCondition(timeCondition, JoinOperator.JOIN_AND);
            }


            ListResultModel<List<LogMsg>> commandMsgs = client.getMsgList(condition);

            userStatusInfo = PageUtil.changPageList(commandMsgs, XUIDataLog.class);

        } catch (
                JDSException e)

        {
            userStatusInfo = new ErrorListResultModel();
            ((ErrorListResultModel) userStatusInfo).setErrcode(e.getErrorCode());
            ((ErrorListResultModel) userStatusInfo).setErrdes(e.getMessage());
        }


        return userStatusInfo;
    }

}
